package exam.controller;

import exam.bean.UserGroup;
import exam.service.UserGroupService;
import exam.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController()
@RequestMapping("/UserGroup")
public class UserGroupController {
    @Autowired
    UserGroupService userGroupService;

    @PreAuthorize("hasAuthority('sys:userGroup:list')")
    @ResponseBody
    @GetMapping("UserGroupInfo")
    public Msg selectInfo(
            @RequestParam(value = "userGroup",defaultValue = "") String userGroup
    ){
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("userGroup",userGroup);
        return Msg.success().add("userGroup",userGroupService.selectInfo(queryMap));
    }

    @PreAuthorize("hasAuthority('sys:userGroup:add')")
    @ResponseBody
    @PostMapping("add")
    public Msg insertInfo(@RequestBody UserGroup userGroup){

        boolean re =  userGroupService.insertInfo(userGroup) > 0 ;
        return Msg.success().setMessage(re ? "添加成功":"添加失败");
    }

//    @PreAuthorize("hasAuthority('sys:userGroup:detail')")
    @ResponseBody
    @GetMapping("/detail")
    public Msg detail(@RequestParam(value="id") int id){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        return Msg.success().add("userGroup",userGroupService.selectInfoSingle(map));
    }

    @PreAuthorize("hasAuthority('sys:userGroup:delete')")
    @ResponseBody
    @GetMapping("/delete")
    public Msg delete (@RequestParam(value="id") int id){
        if(id == 7){
            return Msg.fail().setMessage("默认分组禁止删除！");
        }else if(id == 1){
            return Msg.fail().setMessage("超级管理员分组禁止删除！");
        }
        boolean re = userGroupService.deleteInfo(id) > 0 ;
        return Msg.success().setMessage(re ? "删除成功":"删除失败");
    }

    @PreAuthorize("hasAuthority('sys:userGroup:update')")
    @ResponseBody
    @PostMapping("/upData")
    public Msg update(@RequestBody UserGroup userGroup){
         boolean re = userGroupService.updateInfo(userGroup) > 0;
         return Msg.success().setMessage(re ? "更新成功":"更新失败");
    }
}
